import { defineStore } from 'pinia'
import { ref, watch, onMounted } from 'vue'

export const useShopAddressStore = defineStore('shopAddress', () => {
  const fromAddress = ref([])
  watch(
    fromAddress,
    (newValue) => {
      localStorage.setItem('fromAddress', JSON.stringify(newValue))
    },
    { deep: true }
  )
  const setFromAddress = (val) => {
    fromAddress.value.push(val)
  }
  const delFromAddress = (id) => {
    fromAddress.value = fromAddress.value.filter((item) => item.id !== id)
  }
  const editFromAddress = (val) => {
    for (let item in fromAddress.value) {
      if (fromAddress.value[item].id === val.id) {
        fromAddress.value[item].name = val.name
        fromAddress.value[item].tel = val.tel
        fromAddress.value[item].place = val.place
      }
    }
    console.log(val)
  }
  const clearAddress = () => {
    fromAddress.value = []
    // 同时清除本地存储
    localStorage.removeItem('fromAddress')
  }
  onMounted(() => {
    const storedAddress = localStorage.getItem('fromAddress')
    if (storedAddress) {
      fromAddress.value = JSON.parse(storedAddress)
    }
  })
  return {
    fromAddress,
    setFromAddress,
    clearAddress,
    delFromAddress,
    editFromAddress
  }
})
